// 安全的定时器工具类，符合CSP策略
export class SafeTimer {
  private static timers = new Set<ReturnType<typeof setTimeout>>()
  
  static setTimeout(callback: () => void, delay: number): ReturnType<typeof setTimeout> {
    const timerId = window.setTimeout(() => {
      this.timers.delete(timerId)
      callback()
    }, delay)
    
    this.timers.add(timerId)
    return timerId
  }
  
  static setInterval(callback: () => void, delay: number): ReturnType<typeof setInterval> {
    const timerId = window.setInterval(() => {
      callback()
    }, delay)
    
    this.timers.add(timerId)
    return timerId
  }
  
  static clearTimeout(timerId: ReturnType<typeof setTimeout>): void {
    window.clearTimeout(timerId)
    this.timers.delete(timerId)
  }
  
  static clearInterval(timerId: ReturnType<typeof setInterval>): void {
    window.clearInterval(timerId)
    this.timers.delete(timerId)
  }
  
  static clearAll(): void {
    this.timers.forEach(timerId => {
      window.clearTimeout(timerId)
      window.clearInterval(timerId)
    })
    this.timers.clear()
  }
  
  static getActiveTimers(): ReturnType<typeof setTimeout>[] {
    return Array.from(this.timers)
  }
}

// 安全的Promise延迟工具
export class SafeDelay {
  static delay(ms: number): Promise<void> {
    return new Promise(resolve => {
      const timerId = SafeTimer.setTimeout(resolve, ms)
      return () => SafeTimer.clearTimeout(timerId)
    })
  }
  
  static timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
    return Promise.race([
      promise,
      new Promise<T>((_, reject) => {
        const timerId = SafeTimer.setTimeout(() => {
          reject(new Error('Operation timeout'))
        }, ms)
        return () => SafeTimer.clearTimeout(timerId)
      })
    ])
  }
}

// 安全的网络请求工具
export class SafeNetworkRequest {
  static async fetchWithTimeout(
    url: string, 
    options: RequestInit = {}, 
    timeoutMs: number = 5000
  ): Promise<Response> {
    const controller = new AbortController()
    
    const timeoutId = SafeTimer.setTimeout(() => {
      controller.abort()
    }, timeoutMs)
    
    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal
      })
      
      SafeTimer.clearTimeout(timeoutId)
      return response
    } catch (error) {
      SafeTimer.clearTimeout(timeoutId)
      throw error
    }
  }
  
  static async testConnection(
    url: string = 'https://www.google.com/favicon.ico',
    timeoutMs: number = 3000
  ): Promise<boolean> {
    try {
      await this.fetchWithTimeout(url, {
        method: 'HEAD',
        mode: 'no-cors',
        cache: 'no-cache'
      }, timeoutMs)
      return true
    } catch (error) {
      return false
    }
  }
}
